package models;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;

import play.db.jpa.Model;

/**
 * 
 * @author Omar Darwish
 * @version 1.0
 * 
 */
@Entity
public class RoleInEntity extends Model {


	@ManyToOne
	public EEntity entity;

	@ManyToOne
	public User user;

	@ManyToOne
	public Role role;

	/**
	 * Constructor takes three parameters. The entity, a user in this entity and
	 * his role in it and adds an instance of this Record to each of the entity
	 * and user and Role.
	 * 
	 * @param entity
	 *            A certain entity.
	 * @param user
	 *            A user enrolled in the entity.
	 * @param role
	 *            The role of the user in the entity.
	 */
	public RoleInEntity(EEntity entity, User user, Role role) {
		this.entity = entity;
		this.role = role;
		this.user = user;
		this.entity.addRoleAndUser(this);
		this.role.addUserAndEntity(this);
		this.user.addRoleInEntity(this);
	}

	public List<RoleInEntity> getRoleInEntityOfOrganizer(long userId) {
		List<RoleInEntity> rolesInEntity = RoleInEntity.findAll();
		List<RoleInEntity> rolesOfOrganizer = null;
		for (int i = 0; i < rolesInEntity.size(); i++) {
			if (rolesInEntity.get(i).user.id == userId) {
				rolesOfOrganizer.add(rolesInEntity.get(i));
			}
		}
		return rolesOfOrganizer;

	}

	/**
	 * method to check if a user has any role in a certain entity
	 * 
	 * @author Omar Fouda
	 * @param entity
	 *            , the entity we want to check membership in
	 * @param user
	 *            , user whose membership we want to check
	 * @return Role, reutrn the first role it finds for the user in the
	 *         organization
	 **/

	public static Role findRole(EEntity entity, User user) {
		List<RoleInEntity> list = RoleInEntity.findAll();
		for (RoleInEntity record : list) {
			if (record.entity.id == entity.id && record.user.id == user.id) {

				return record.role;
			}

		}
		return null;
	}

	/**
	 * @author Ahmed Mahmoud
	 * @return
	 * 
	 */
	public boolean cascadeDelete() {
		entity.rolesAndUsers.remove(this);
		entity.save();
		user.rolesAndEntities.remove(this);
		user.save();

		this.delete();
		return true;
	}

}
